package com.dongdong.android.framework.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.dongdong.android.framework.BuildConfig;
import com.dongdong.android.framework.http.webservice.UserService;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dongdong on 2018/3/26.
 */

public class ApiManager {

    private static ApiManager instance;
    public static final long DEFAULT_TIMEOUT = 10000L;

    private Retrofit retrofit;
    public UserService userService;


    public static ApiManager getInstance() {
        if (instance == null) {
            synchronized (ApiManager.class) {
                if (instance == null) {
                    instance = new ApiManager();
                }
            }
        }
        return instance;
    }

    private ApiManager() {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create();
        retrofit = new Retrofit.Builder()
                // okhttp的实现
                .client(getOkHttpClient())
                // RxJava支持 返回类型适配
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                // Gson支持 数据解析
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(BuildConfig.Base_Url)
                .build();

        //各个接口类的实现
        userService = retrofit.create(UserService.class);

    }


    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(getOkHttpLogInterceptor());
        }
        builder.sslSocketFactory(createSSLSocketFactory());
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // 其他设置
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                // 错误重连
                .retryOnConnectionFailure(true);


        return builder.build();
    }

    /**
     * 日志管理拦截器
     *
     * @return
     */
    private HttpLoggingInterceptor getOkHttpLogInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;

    }

    private SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }


}
